<?php
class picture extends top
{
	//重定义构造函数
    function __construct(){  
        parent::__construct();
        //定义当前导航
        $this->nav_name = 'picture';
        $this->page_title = '相册管理';
        $this->breadcrumb += array('1'=>array('name'=>'相册','url'=>spUrl('picture')));

    }
	function index(){
		$data = $this->spArgs();
		//获取当前分类id
		$cat_id = isset($data['cat_id'])?$data['cat_id']:0;
		//构造左侧导航
		$cat_id = $this->__left_nav($cat_id);
		
		if(!is_numeric($cat_id)) $this->__yt_error();
		$this->left_nav_id = $cat_id;
		$this->cat_id =  $cat_id;
		//构造面包屑导航
		$category = spClass("m_category");
		$cat_info  = $category->find(array('id'=>$cat_id));
		if(empty($cat_info)) $cat_info=array('name'=>"全部",'id'=>0);
		$this->breadcrumb += array(
					'2'=>array('name'=>$cat_info['name'],'url'=>spUrl('picture','index',array('cat_id'=>$cat_info['id']))),
        			'3'=>array('name'=>'列表')
        		);

		//成功添加、更新图片后的提示
		$notice = array($data['state'],$data['message']);
		
		//更新属性
		$picture = spClass("m_picture");
		if($data['picture_update']){
			if(1){
				if(isset($data['weight']))				
					$data_update = array('weight'=>$data['weight']);
				elseif(isset($data['visible']))
					$data_update = array('visible'=>$data['visible']);
				else
					$this->__yt_error();

				if($picture->update('id='.$data['picture_id'],$data_update)){
					$notice = array('success','更新成功！');
				}else{
					$notice = array('danger','更新出错！');
				}
			}else{
				$notice = array('danger','更新有误！');
			}
		}
		//删除图片
		if($data['delete_picture_id']){
			if($picture->delete('id='.$data['delete_picture_id'])){
				unlink(iconv("utf-8","gbk",$data['picture_dir']));
				unlink(iconv("utf-8","gbk",$data['picture_dir'].'_temp.jpg'));
				$notice = array('success','删除成功！');
			}else{
				$notice = array('danger','删除出错！');
			}
		}	
		$this->notice = $notice[0]?$notice:null;
		
		//查找图片
		
		if($data['s_submit']){
			$where = "( title like '%" .$data['s_content']. "%' OR description like '%" .$data['s_content']. "%' ) ";
			if($cat_info['id']!=0){	
				$where .= " AND cat_id='".$cat_id."'";
			}
		}else{
			if($cat_info['id']!=0){
				$where = "cat_id='".$cat_id."'";
			}else{
				$where = "";
			}
		}
		$sort= 'weight DESC,add_time DESC';
		$fields = 'id,title,dir,description,view_num,add_time,visible,weight';
		$picture_result = $picture->spPager($this->spArgs('page', 1), 10)->findAll($where,$sort,$fields);
		$this->pager = $picture->spPager()->getPager();
		$this->picture_result = $picture_result;

		$this->c = 'picture';
		$this->a = 'index';		
		$this->data_return = $data;
	}	
	function add(){
		$data = $this->spArgs();
		var_dump($data);
		
		//获取当前分类id
		$cat_id = isset($data['cat_id'])?$data['cat_id']:0;
		//构造左侧导航
		$cat_id = $this->__left_nav($cat_id);
		
		if(!is_numeric($cat_id)) $this->__yt_error();
		$this->left_nav_id = $cat_id;
		$this->cat_id =  $cat_id;
		//构造面包屑导航
		$category = spClass("m_category");
		$cat_info  = $category->find(array('id'=>$cat_id));
		if(empty($cat_info)) $cat_info=array('name'=>"全部",'id'=>0);
		$this->breadcrumb += array(
					'2'=>array('name'=>$cat_info['name'],'url'=>spUrl('picture','index',array('cat_id'=>$cat_info['id']))),
        			'3'=>array('name'=>'添加')
        		);
		//批量更新标题
		if($data['submit']){
			$picture = spClass("m_picture");
			for($i=0;$data['title'][$i];$i++){
				if(1){
					$is_ok[$i] = $picture->update(array('id'=>$data['id'][$i]),array('title'=>$data['title'][$i],'description'=>$data['description'][$i]));
				}else{
					$is_ok[$i] = 0;		
				}
			}
			if(!in_array(0,$is_ok)){
				$this->jump(spUrl('picture', 'index',array('cat_id'=>$data['cat_id'],'state'=>'success','message'=>'添加成功！','content_only'=>$this->content_only))); 
			}else{
				$this->jump(spUrl('picture', 'index',array('cat_id'=>$data['cat_id'],'state'=>'danger','message'=>'添加出错！','content_only'=>$this->content_only))); 
			}
		}
	}
	function opera(){
		$data = $this->spArgs();
		//获取当前分类id
		$cat_id = isset($data['cat_id'])?$data['cat_id']:0;
		//构造左侧导航
		$cat_id = $this->__left_nav($cat_id);
		
		if(!is_numeric($cat_id)) $this->__yt_error();
		$this->left_nav_id = $cat_id;
		$this->cat_id =  $cat_id;
		//构造面包屑导航
		$category = spClass("m_category");
		$cat_info  = $category->find(array('id'=>$cat_id));
		if(empty($cat_info)) $cat_info=array('name'=>"全部",'id'=>0);
		$this->breadcrumb += array(
					'2'=>array('name'=>$cat_info['name'],'url'=>spUrl('picture','index',array('cat_id'=>$cat_info['id']))),
					'3'=>array('name'=>"添加")
        		);

		//默认为添加
		$data_return = array('update_add'=>"添加",'cat_id'=>$cat_id);
		//更新
		$picture = spClass("m_picture");
		if(is_numeric($data['update_picture_id'])){	
			$data_return = $picture->find(array('id'=>$data['update_picture_id']));
			if(empty($data_return)) $this->__yt_error();
			$data_return['update_add'] = "更新";
			$breadcrumb = $this->breadcrumb;
			$breadcrumb['3'] = array('name'=>$data_return['title']);
			$breadcrumb['4'] = array('name'=>"更新");
			$this->breadcrumb = $breadcrumb;
		}
		//提交
		if($data['submit']){
			if(1){
				$data_insert = array(
					'editor_id'=>$_SESSION['ID'],
					'cat_id'=>$data['cat_id'],
					'title'=>$data['title'],
					'description'=>$data['description'],
					'dir'=>$data['dir']?$data['dir']:0,
					'height'=>$data['height']?$data['height']:0,
					'add_time'=>$data['add_time'],
				);

				if($data['id']){
					$is_ok = $picture->update('id='.$data['id'],$data_insert);
				}else{
					$is_ok = $picture->create($data_insert);
				}
				if($is_ok){
					$this->jump(spUrl('picture', 'index',array('cat_id'=>$data['cat_id'],'state'=>'success','message'=>$data['update_add'].'成功！','content_only'=>$this->content_only))); 
				}else{
					$data_return = $data;
					$this->notice = array('danger',$data['update_add'].'出错！');
				}
			}else{
				$data_return = $data;
				$this->notice = array('danger','填写有误！');				
			}
		}
		$this->data_return = $data_return;
	}
	//生成略缩图
	function make_new_img_header($targetFile){
		$ifn = iconv("utf-8","gbk",$targetFile);
		$img_type = pathinfo($ifn, PATHINFO_EXTENSION);
        switch ($img_type) { 
            case 'jpg': 
                $source=@imagecreatefromjpeg($ifn); 
                break; 
            case 'jpeg': 
                $source=@imagecreatefromjpeg($ifn); 
                break; 
            case 'jpe': 
                $source=@imagecreatefromjpeg($ifn); 
                break; 
            case 'gif': 
                $source=@imagecreatefromgif($ifn); 
                break; 
            case 'png': 
                $source=@imagecreatefrompng($ifn); 
                break; 
            default: 
                return false; 
                break;//只能处理jpg、gif或png格式的图片 
        } 
	    $sourceWidth = imagesx($source);
	    $sourceHeight = imagesy($source);
		

	    $thumbWidth = 194;
	    $thumbHeight = 194*$sourceHeight/$sourceWidth;
	    $thumb = imagecreatetruecolor($thumbWidth, $thumbHeight);		
	    imagecopyresampled($thumb, $source, 0, 0, 0, 0, 194, $thumbHeight, $sourceWidth, $sourceHeight);	
		imagejpeg($thumb,iconv("utf-8","gbk",$targetFile.'_temp.jpg'),95);
		imagedestroy($thumb);
		return $thumbHeight;
	}
	function picture_ajax(){
		if (!empty($_FILES)) {
			$tempFile = $_FILES['Filedata']['tmp_name'];

			$data = $this->spArgs();
			//相对根目录路径
			$targetFolder = 'uploads/pic/' . 'cat_id_' . $data['cat_id'];
			//定义存储路径
			$www_dir = substr($_SERVER['SCRIPT_FILENAME'],0,-9);
			$targetPath = $www_dir.'../'. $targetFolder;
			//不存在则新建
			if(!is_dir($targetPath)){
				mkdir($targetPath, 0777);
			}
			//检验文件格式
			$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
			$fileParts = pathinfo($_FILES['Filedata']['name']);
			//图片标题
			$title_return = preg_replace("/\.[^\.]+$/",'',$_FILES['Filedata']['name']);
			$title = time().rand(0,10000).$data['cat_id'].$data['session_id'];
			//扩展名变小写
			$fileParts['extension'] = strtolower($fileParts['extension']);
			//重命名文件
			/*
			if(file_exists(iconv("utf-8","gbk", $targetPath. '/' . $_FILES['Filedata']['name']))){
				$cms_file_name = $title.'_'.time().'.'.$fileParts['extension'];
			}else{
				$cms_file_name = $title.'.'.$fileParts['extension'];
			}
			*/
			$cms_file_name = $title.'.'.$fileParts['extension'];
			//定义文件路径
			$targetFile =  str_replace('//','/',$targetPath) .'/'.$cms_file_name;	
			
			if (in_array($fileParts['extension'],$fileTypes)) {
				//中文路径转换编码，存入
				move_uploaded_file($tempFile,iconv("utf-8","gbk", $targetFile));
				//生成略缩图
				$height = $this->make_new_img_header($targetFile);
				//存入数据库				
				$picture = spClass("m_picture");
				$data_insert = array(
					'editor_id'=>$data['session_id'],
					'cat_id'=>$data['cat_id'],
					'title'=>$title_return,
					'dir'=>$targetFolder.'/'.$cms_file_name,
					'description'=>'',
					'height'=>$height
				);
				$is_ok = $picture->create($data_insert);
				if($is_ok){
					//返回页面结果
					$result = array(
						'dir'=>$targetFolder.'/'.$cms_file_name,
						'name'=>$title_return,
						'id'=>$is_ok
					);
					echo json_encode( $result );
				}else{
					echo '存入数据库失败';
				}
			} else {
				echo '文件格式不正确';
			}
		}
	}
}